package org.batatasframework.support.database.values;

import java.sql.ResultSet;
import java.text.DecimalFormat;

import org.batatasframework.support.database.spi.ResultWritable;
import org.batatasframework.support.database.sql.field.SelectFragment;


public class DecimalValueHolder extends AbstractSingleValueHolder{

	private final DecimalFormat format;
	
	public DecimalValueHolder(SelectFragment field, String alias, Object format) {
		super(field, alias);

		if(format instanceof DecimalFormat){
			this.format = (DecimalFormat)format;
		}else{
			this.format = null;
		}
	}

	@Override
	public FieldValue read(ResultSet rs) throws Exception {
		return new DecimalValue(rs.getDouble(alias));
	}

	@Override
	public StatisticsTotal createStatistics() {
		return new DecimalStatistics();
	}
	
	class DecimalStatistics implements StatisticsTotal{

		private double sumValue;
		
		private class DecimalStatisticsValue implements StatisticsValue{
			private double value;
			
			@Override
			public void read(ResultSet rs) throws Exception {
				double val = rs.getDouble(alias);
				value += val;
				sumValue += val;
			}

			@Override
			public void writeTo(ResultWritable resultWriter) throws Exception {
				if(null == format){
					resultWriter.append(value);
				}else{
					resultWriter.append(format.format(value));
				}
			}
			
		}
		
		@Override
		public StatisticsValue newValue() {
			return new DecimalStatisticsValue();
		}

		@Override
		public void writeTo(ResultWritable resultWriter) throws Exception {
			if(null == format){
				resultWriter.append(sumValue);
			}else{
				resultWriter.append(format.format(sumValue));
			}
		}
		
		@Override
		public String[] getItemNames() {
			return null;
		}

	}
	
	class DecimalValue extends AbstractValue<Double>{
		
		public DecimalValue(Double value) {
			super(value);
		}

		@Override
		public Object targetValue() {
			if(null == format) return value;
			return format.format(value.doubleValue());
		}
	}
}
